<?php namespace Home\Controller;
require 'App/Home/Function/functions.php';

class IndexController extends \Hdphp\Controller\Controller{

	public function __init()
	{
		//分配栏目
		$this->assignCat();

	}

	//分配栏目数据
	protected function assignCat()
	{
		$data = Db::table('shop_cat')->get();
		$data = Data::channelLevel($data,  0, "&nbsp;",'cat_id') ;
		View::with('cat',$data);

	}
	//商城首页
	public function index()
	{
		View::make('Template/index.html');
	}
	//商品列表页
	public function lists()
	{
		if(!isset($_GET['s']))
		{
			$this->formatUrl();
		}
		//分配列表页用到的搜索属性
		// $this->assignCateogrySearchAttr();

		//分配列表页商品
		$this->assignCategoryGoodsList();

		View::make('Template/lists.html');
	}

	//分配列表页商品
	private function assignCategoryGoodsList()
	{
		//搜索属性
		$s = explode('-',$_GET['s']);
		$s = array_filter($s);
		if(empty($s))
		{
			
			//没有选择属性的情况
			// $goodsCount=Db::table('shop_goods')->where('cat_id',$_GET['cat_id'])->count();
			// p($goodsCount);exit;
			// $page = Page::make($goodsCount);
			// $goods = Db::table('shop_goods')->where('cat_id',$_GET['cat_id'])->limit(Page::limit())->get();
			$goods = Db::table('shop_goods')->get();
			p($goods);
			// View::with('page',$page);
			View::with('goods',$goods);
		}
		else
		{
			//按用户筛选的属性检索
			$searchAttr = "'".implode("','", $s)."'";
			$sql ="
			SELECT count(*) as c FROM (
				(SELECT * FROM hd_shop_goods_attr 
				WHERE attr_value IN(".$searchAttr.") GROUP BY goods_id 
				HAVING count(*)=".count($s).") AS g)";
			$d = Db::select($sql);
			$page = Page::make($d[0]['c']);

			//获取商品
			$sql ="SELECT * FROM hd_shop_goods g JOIN hd_shop_goods_attr ga
			ON g.goods_id =ga.goods_id
				WHERE attr_value IN(".$searchAttr.") GROUP BY ga.goods_id 
				HAVING count(*)=".count($s)." LIMIT ".Page::limit();
				$goods = Db::select($sql);
			View::with('page',$page);
			View::with('goods',$goods);
		}
	}

	//如果GET中不存在s变量，生成带有s搜索属性的变量并跳转
	private function formatUrl()
	{
		$cat = Db::table('shop_cat')->where('cat_id',$_GET['cat_id'])->first();
		//获取栏目的类型属性
		$attr = Db::table('shop_attr')->where('shop_type_id',$cat['type_id'])->get();
		$url =  __URL__.'&s=';
		for($i=0;$i<count($attr);$i++)
		{
			$url.='0-';
		}
		go(substr($url,0,-1));

	}

	//分配列表页搜索属性
	private function assignCateogrySearchAttr()
	{
		$cat = Db::table('shop_cat')->where('cat_id',$_GET['cat_id'])->first();
		//获取栏目的类型属性
		$attr = Db::table('shop_attr')->where('shop_type_id',$cat['type_id'])->get();
		foreach($attr as $k=>$v)
		{
			$attr[$k]['attr_value']=Db::table('shop_goods_attr')
			->where('attr_id',$v['attr_id'])->groupBy('attr_value')->get();
		}
		View::with('searchAttr',$attr);
	}

	public function goods()
	{

	}
}








